package org.yi.web.ajax;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.annotation.Action;
import org.yi.core.common.Constants;
import org.yi.core.enums.RoleEnum;
import org.yi.core.helper.DuoshuoHelper;
import org.yi.web.account.entity.AccountEntity;
import org.yi.web.base.BaseController;
import org.yi.web.favorite.FavoriteEntity;
import org.yi.web.post.entity.PostEntity;

import com.jfinal.plugin.ehcache.CacheKit;

@Action(action = "/ajax")
public class AjaxController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(AjaxController.class);
	
	public void index() {
		
	}
	
	public void login() {
		Map<String,Object> result = new HashMap<String,Object>();
		String email = getPara("email");
		String password = getPara("password");
        try {
        	AccountEntity account = AccountEntity.dao.getByEmail(email);
            if(account == null){
            	result.put("message", "邮箱不存在!");
            	result.put("result", false);
            } else if(!DigestUtils.md5Hex(password +"{" + account.getStr("login_name") + "}").equals(account.get("passwd"))) {
            	result.put("message", "密码错误!");
            	result.put("result", false);
            } else {
            	account.set("login_time", Calendar.getInstance().getTime());
            	account.update();
            	getSession().setAttribute(Constants.FRONT_LOGIN_USER, account);
				result.put("result", true);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put("result", false);
            result.put("message", "unknow error:" + e.getMessage());
		}
		renderJson(result);
	}
	
	public void bind() {
		regist();
	}
	
	public void regist(){
		Map<String,Object> result = new HashMap<String,Object>();
		String userName = getPara("username");
		String email = getPara("user_email");
		String password = getPara("user_pass");
		try {
			if(AccountEntity.dao.getByName(userName) != null) {
				result.put("message", "用户 [" + userName + "] 已存在!");
				result.put("result", false);
			} else if(AccountEntity.dao.getByEmail(email) != null) {
				result.put("message", "邮箱 [" + email + "] 已存在!");
				result.put("result", false);
			} else if(StringUtils.isBlank(password)) {
				result.put("message", "密码不能为空!");
				result.put("result", false);
			} else {
				AccountEntity account = new AccountEntity();
				account.set("login_name", userName);
				account.set("passwd", password);
				account.set("email", email);
				account.set("role", RoleEnum.REGISTER_USER.getCode());
				account.set("passwd", DigestUtils.md5Hex(password +"{" + userName + "}"));
				account.set("sso_id", getPara("sso_id"));
				account.set("sso_type", getPara("sso_type"));
				account.set("create_time", Calendar.getInstance().getTime());
				account.set("login_time", Calendar.getInstance().getTime());
				account.save();
				getSession().setAttribute(Constants.FRONT_LOGIN_USER, account);
				DuoshuoHelper.token(account, getRequest(), getResponse());
				result.put("message", "注册成功!");
				result.put("result", true);
			}
		} catch (Exception e) {
			logger.error("注册新用户 [" + userName + "] 失败，" + e.getMessage(), e);
			result.put("message", "注册新用户 [" + userName + "] 失败!");
			result.put("result", false);
		}
		renderJson(result);
	}
	
	/**
	 * ajax判断用户是否可注册
	 */
	public void userExist() {
		renderJson(AccountEntity.dao.userExist(getPara("key")));
	}
	
	/**
	 * ajax判断用户是否可注册
	 */
	public void emailExist() {
		renderJson(AccountEntity.dao.emailExist(getPara("key")));
	}
	
	/**
	 *  用户退出登录
	 */
	public void logout(){
		Map<String,Object> obj = new HashMap<String,Object>();
		getSession().invalidate();
		obj.put("result", true);
		renderJson(obj);
	}
	
	public void subscribe() {
//		String email = getPara("email");
		
	}
	/**
	 * 文章喜欢
	 */
	public void like() {
		String articleId = getPara("pid");
		try {
			if(StringUtils.isNotBlank(articleId)) {
				PostEntity.dao.like(articleId);
			}
			renderJson(true);
		} catch (Exception e) {
			logger.error("点赞出错,文章ID：" + articleId, e);
			renderJson(false);
		}
	}
	
	public void addFavorite() {
		Map<String,Object> result = new HashMap<String,Object>();
		final String articleId = getPara("pid");
		try {
			AccountEntity frontUser = getFrontUser();
			if(frontUser != null && NumberUtils.isDigits(String.valueOf(frontUser.get("id")))) {
				if(StringUtils.isNotBlank(articleId)) {
					FavoriteEntity findByUidAid = FavoriteEntity.dao.findByUidAid(frontUser.get("id"), articleId);
					// 没有收藏过，则插入收藏表并更新收藏数量
					if(findByUidAid == null) {
						FavoriteEntity entity = new FavoriteEntity();
						entity.set("user_id", frontUser.get("id"));
						entity.set("article_id", articleId);
						entity.set("create_time", Calendar.getInstance().getTime());
						entity.save();
						PostEntity.dao.updateFavorite(articleId, true);
						// update cache
						CacheKit.put(Constants.CACHE_KEY_MID, "user"+getFrontUser().get("id")+"_article"+articleId+"_Favorite", entity);
					}
					result.put("result", true);
				} else {
					result.put("result", false);
					result.put("message", "参数错误");
				}
			} else {
				result.put("result", false);
				result.put("message", "登陆后才能收藏");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.put("result", false);
			result.put("message", "服务端错误");
		}
		renderJson(result);
	}
	
	public void removeFavorite() {
		Map<String,Object> result = new HashMap<String,Object>();
		String articleId = getPara("pid");
		try {
			AccountEntity frontUser = getFrontUser();
			if(frontUser != null && NumberUtils.isDigits(String.valueOf(frontUser.get("id")))) {
				if(StringUtils.isNotBlank(articleId)) {
					
					FavoriteEntity findByUidAid = FavoriteEntity.dao.findByUidAid(frontUser.get("id"), articleId);
					// 收藏过，则插入删除收藏表相关记录并更新收藏数量
					if(findByUidAid != null) {
						FavoriteEntity.dao.deleteByUidAid(frontUser.get("id"), articleId);
						PostEntity.dao.updateFavorite(articleId, false);
						// remove from cache
						CacheKit.remove(Constants.CACHE_KEY_MID, "user"+getFrontUser().get("id")+"_article"+articleId+"_Favorite");
					}
					result.put("result", true);
				} else {
					result.put("result", false);
					result.put("message", "参数错误");
				}
			} else {
				result.put("result", false);
				result.put("message", "登陆后才能收藏");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.put("result", false);
			result.put("message", "服务端错误");
		}
		renderJson(result);
	}
}
